package app.itgungnir.compose.wan.business.main.home

import androidx.lifecycle.ViewModel
import androidx.paging.*
import app.itgungnir.compose.wan.utils.*
import app.itgungnir.compose.wan.widgets.BannerItem
import com.google.gson.JsonElement
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class HomeViewModel : ViewModel() {

    val bannerFlow = WanDatabase.dao.queryHomeBanners().map {
        it.map { item -> BannerItem(coverUrl = item.imagePath, linkUrl = item.url) }
    }

    val hotArticleFlow = WanDatabase.dao.queryHomeHotArticles()

    val articleFlow: Flow<PagingData<HomeArticle>> = pagingSourceWithCache(
        firstPageIndex = 0,
        pageSize = 20,
        networkRequest = {
            wanAndroidService.getHomeArticles(pageNo = it).wanResponse<WanPagingResponse<HomeArticle>>()
        },
        queryCache = { dao -> dao.queryHomeArticles() },
        clearCache = { dao -> dao.deleteAllHomeArticles() },
        appendCache = { list, dao -> dao.insertAllHomeArticles(list) }
    )

    init {
        getBannerList()
        getHotArticles()
    }

    fun getBannerList() = launch {
        wanAndroidService.getBanners().wanResponse<List<HomeBanner>>()?.let {
            WanDatabase.dao.deleteAllHomeBanners()
            WanDatabase.dao.insertAllHomeBanners(it)
        }
    }

    fun getHotArticles() = launch {
        wanAndroidService.getHotArticles().wanResponse<List<HomeArticle>>()?.let {
            WanDatabase.dao.deleteAllHomeHotArticles()
            WanDatabase.dao.insertAllHomeHotArticles(it)
        }
    }

    fun collectArticle(articleId: Long?) = launch {
        articleId ?: return@launch
        wanAndroidService.collectArticle(articleId).wanResponse<JsonElement>()
        WanDatabase.instance.dao().updateHomeArticleCollect(articleId, true)
    }

    fun uncollectArticle(articleId: Long?) = launch {
        articleId ?: return@launch
        wanAndroidService.uncollectArticle(articleId).wanResponse<JsonElement>()
        WanDatabase.instance.dao().updateHomeArticleCollect(articleId, false)
    }
}
